package com.zsr.example.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsr.example.config.annotation.OptLog;
import com.zsr.example.config.annotation.RequiresPermissions;
import com.zsr.example.dto.session.WebsocketMessageDTO;
import com.zsr.example.entity.TChatRecord;
import com.zsr.example.entity.UcenterMember;
import com.zsr.example.service.TChatRecordService;
import com.zsr.example.service.UcenterMemberService;
import com.zsr.example.service.impl.TokenService;
import com.zsr.example.service.impl.WebSocketServiceImpl;
import com.zsr.example.util.CommonUtil;
import com.zsr.example.util.constants.ChatTypeEnum;
import com.zsr.example.util.constants.SysConstants;
import com.zsr.example.vo.MemberReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import static com.zsr.example.util.constants.SysLogConstants.DELETE;
import static com.zsr.example.util.constants.SysLogConstants.LOCK;

/**
 * <p>
 * 会员表 后端控制器
 * </p>
 *
 * @author zsr
 * @since 2021-12-04
 */
@RestController
@CrossOrigin
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private UcenterMemberService ucenterMemberService;
    @Autowired
    private WebSocketServiceImpl webSocketService;
    @Autowired
    private TChatRecordService chatRecordService;
    @Autowired
    private TokenService tokenService;

    @RequiresPermissions("member:list")
    @PostMapping("pageListMemberCondition/{current}/{limit}")
    public JSONObject pageListLogCondition(
            @PathVariable long current,
            @PathVariable long limit,
            @RequestBody(required = false) MemberReq memberReq) {//@RequestBody
        // 使用json封装到参数,需要post请求
        //创建page对象
        Page<UcenterMember> page = new Page<>(current, limit);

        ucenterMemberService.pageQuery(page, memberReq);

        long total = page.getTotal();//总记录数
        List<UcenterMember> records = page.getRecords(); //数据list集合

        return CommonUtil.successPage(total, records);
    }

    /**
     * 冻结用户
     */
    @OptLog(optType = LOCK,optDesc = "冻结用户")
    @RequiresPermissions("member:disabled")
    @PostMapping("disabledMember/{id}")
    public JSONObject disabledMember (@PathVariable String id,@RequestBody(required = false) String disableReason){
        UcenterMember member = ucenterMemberService.getById(id);

        member.setIsDisabled(!member.getIsDisabled())
        .setDisableReason(JSON.parseObject(disableReason).getString("disableReason"));
        ucenterMemberService.updateById(member);
        return CommonUtil.success();
    }

    /**
     * 获取在线用户
     */
    @RequiresPermissions("member:list")
    @GetMapping("getOnline")
    public JSONObject getOnline(){
        Set<String> ids = WebSocketServiceImpl.getClients().keySet();
        return CommonUtil.successJson(ids);
    }
    @RequiresPermissions("member:list")
    @PostMapping("sendMsg")
    public JSONObject sendMsg(@RequestBody JSONObject jsonObject){
        String id = jsonObject.getString("id");
        String msg = jsonObject.getString("msg");
        try {
            WebsocketMessageDTO messageDTO = WebsocketMessageDTO.builder()
                    .data(msg)
                    .type(ChatTypeEnum.SEND_MESSAGE.getType())
                    .build();
            webSocketService.sendMessageTo(JSON.toJSONString(messageDTO),id);
        } catch (IOException e) {
            e.printStackTrace();
        }
        TChatRecord chatRecord=new TChatRecord();
        chatRecord.setContent(msg);
        int userId = tokenService.getUserInfo().getUserId();
        chatRecord.setFromMemberId(String.valueOf(userId));
        chatRecord.setToMemberId(id);
        chatRecord.setType(SysConstants.ADMIN);
        chatRecord.setStatus(SysConstants.STATUS_NO_READ);
        chatRecordService.save(chatRecord);
        return CommonUtil.successJson();
    }

}

